package com.cg.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cg.listener.CrawlerCsvReadListener;
import com.cg.mapper.CrawlerJavaMapper;
import com.cg.service.CrawlerImportService;
import com.cg.vo.CrawlerJavaRow;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class CrawlerImportServiceImpl implements CrawlerImportService {

    private final CrawlerJavaMapper crawlerJavaMapper;

    @Override
    public void importCsvFromResources() {
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:crawler/*.csv");
            for (Resource resource : resources) {
                String filename = resource.getFilename();
                if (filename == null) continue;
                // 规则：qcwy_java.csv -> crawler_py_java
                String key = filename.replace("qcwy_", "").replace(".csv", "");
                String table = "crawler_py_" + key;
                log.info("开始导入CSV: {} -> 表: {}", filename, table);
                EasyExcel.read(resource.getInputStream(), CrawlerJavaRow.class,
                                new CrawlerCsvReadListener(crawlerJavaMapper, table))
                        .excelType(ExcelTypeEnum.CSV)
                        .autoCloseStream(true)
                        .sheet()
                        .doRead();
                log.info("导入完成: {}", filename);
            }
        } catch (Exception e) {
            log.error("导入CSV失败", e);
        }
    }
}


